package com.itheima.filter;

import com.itheima.exception.BusinessException;
import com.itheima.utlis.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //0.强转对象
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //1.获取请求url路径
        String url = req.getRequestURI();

        //2.判断请求路径是否为登录路径
        if (url.contains("login")){
//            登录操作放行
            filterChain.doFilter(servletRequest,servletResponse);
//            结束当前方法不应该往下走
            return;
        }
        //3.获取请求头中的令牌token
        String token = req.getHeader("token");
        //4.判断令牌是否存在，不存在响应401
        if (token==null){
            resp.setStatus(401);   //设置响应状态码
            log.error("令牌为空");
           // throw new BusinessException("用户未登录");
            //            结束当前方法不应该往下走
            return;

        }
        //5.解析token，如果解析失败响应401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("当前用户："+claims.getSubject());
        } catch (Exception e) {
            resp.setStatus(401);
            log.error("令牌解析失败{}",e.getMessage());
           // throw new BusinessException("未登录");
            //            结束当前方法不应该往下走
            return;
        }

        //6.放行
        filterChain.doFilter(servletRequest,servletResponse);

    }

}
